{% load i18n %}

<script type="text/javascript">
<!--

var moviePlayerID = 'moviePlayer';
var player = null;
var currentID = null;
var bufferingTimeout = null;
var randomTime = null;
var videoList = new Array();
var videoPlayIndex = -1;

/* functions */
{% ifequal channel 'highlight' %}
function buildPlaylist() {
	var title = $('#playlistTitle').attr('value');
	if ('' == trim(title)) {
		alert('{% trans "Please input playlist title!" %}');
		return;
	} else {
		document.location.href = 'http://{{ siteHostname }}/playlist/add'
		+ '?store=' + ($('#storePlaylist').attr('checked') ? '1' : '0') 
		+ '&title=' + escape(title)
		+ '&videoIDs=' + $.cookie('highlightVideos');
	}
}
{% endifequal %}

{% if playlistEditable %}
function editPlaylist() {
	if ($('#buildPlaylist').length > 0) {
		$('#buildPlaylist').css('display', 'none');
	}
	$('#editLink').css('display', 'none');
	$('#editBox').css('display', '');
	$('#editBox').load('http://{{ siteHostname }}/playlist/edit/{{ playlistKey }}');
}
{% endif %}

function initVideoList() {
	var highlightVideos = '{{ videoIDs }}';
	var hlvideoList = highlightVideos.split(',');
	var i = 0;
	for (i=0; i<hlvideoList.length; i++) {
		videoList[videoList.length] = hlvideoList[i];
	}
	videoPlayIndex = -1;
}

function loopThisVideo() {
	if (currentID) {
		document.location.href = 'http://{{ siteHostname }}/loop/youtube/' + currentID;
	}
}

function playMovie(url)
{
	player.sendEvent('LOAD', url);
}

function setMovieData(title, videoID, sourceURL, artist, song)
{
	var now = new Date();
	$('#nowPlaying').html('{% trans "Now Playing" %}: <b>' + title + '</b>');
{% if not isPlaylist %}
	if (artist != undefined && song != undefined) {
		moreParams = ", '"+escape(artist)+"', '"+escape(song)+"'";
	} else {
		moreParams = "";
	}
	$('#recentlyPlayed').prepend('<li>' + now.toTimeString().substr(0, 5) + ': ' 
										+ '<span class="highlightLink" id="highlight-' + videoID + '"><img src="/static/images/ajax-loader.gif" width="12" height="12"/></span>'
										+ '<a href="javascript:loadMovieDataByVideoID(\'' + videoID + '\''+moreParams+');">' 
										+ title + '</a></li>');
	if ($('#recentlyPlayed li').length > 30) {
		$('#recentlyPlayed li:last').remove();
	}
	renderHighlightLink(videoID);
{% else %}
	if (currentID) {
		$('#playlist-'+currentID+' .title').removeClass('bold');
	}
	$('#playlist-'+videoID+' .title').addClass('bold');
	var index=-1;
	var i=0;
	for (i=0; i<videoList.length; i++) {
		if (videoID == videoList[i]) {
			index = i;
			break;
		}
	}
	if (index >= 0) {
		videoPlayIndex = index;
	}
{% endif %}
}

function setRandomTime() {
	if (null == randomTime) {
		randomTime = new Date();
	}
}

function isInRandomTime() {
	var now = new Date();
	if (randomTime && ((now.getTime()-randomTime.getTime()) < (1000 * 60 * 5))) {
		return true;
	} else {
		randomTime = null;
		return false;
	}
}

function startRandom()
{
	$('#playButton').html('{% trans "Play another!" %}');
//	if (currentID) {
		setRandomTime();
		loadNextMovieData(true);
//	}
}
function fillYouTubeVideoData(data, textStatus) {
	var id = data.targetID;
	if (1 == data.success) {
		var title = data.videoTitle;
		var videoID = data.videoID;
		$('#'+id).html('<span class="highlightLink" id="highlight-' + videoID + '"><img src="/static/images/ajax-loader.gif" width="12" height="12"/></span>'
						+ '<a href="javascript:loadMovieDataByVideoID(\'' + videoID + '\', \''+escape(data.artist)+'\', \''+escape(data.song)+'\');">' 
						+ title + '</a>');
		renderHighlightLink(videoID);
	} else {
		$('#'+id).children('img').remove();
	}
}

function fillArtistListItem(data, textStatus) {
	var id = data.targetID;
	if (1 == data.success) {
		var videoID = data.videoID;
		$('#'+id).html('<img src="/static/images/ajax-loader.gif" width="12" height="12"/>'+data.artist+' - '+data.track);
		$.getJSON('http://{{ siteHostname }}/channel/fetch/youtuberesult?song='+escape(data.track)+'&artist='+escape(data.artist)+'&targetID='+id, fillYouTubeVideoData);
	} else {
		$('#'+id).children('img').remove();
	}
}

function loadSimilarSongList(data, textStatus) {
	if (1 == data.success) {
		$('#similarSongs').html('<ul id="similarSongList"></ul>');
		var numResults = data.numResults;
		if (0 == numResults) {
			$('#similarSongsBlock').css('display', 'none');
		} else {
			for (var i=0; i<numResults; i++) {
				var songData = data[i];
				var id = 'similarsong_'+i;
				if (data.fromSimilarArtists) {
					$('#similarSongList').append('<li id="'+id+'"><img src="/static/images/ajax-loader.gif" width="12" height="12"/>'+songData.artist+' - ...</li>');
					$.getJSON('http://{{ siteHostname }}/channel/fetch/artisttrack?artist='+escape(songData.artist)+'&targetID='+id, fillArtistListItem);
				} else {
					$('#similarSongList').append('<li id="'+id+'"><img src="/static/images/ajax-loader.gif" width="12" height="12"/>'+songData.artist+' - '+songData.track+'</li>');
					$.getJSON('http://{{ siteHostname }}/channel/fetch/youtuberesult?song='+escape(songData.track)+'&artist='+escape(songData.artist)+'&targetID='+id, fillYouTubeVideoData);
				}
			}
		}
	} else {
		$('#similarSongsBlock').css('display', 'none');
	}	
}

function getSimilarSongs(song, artist) {
	$('#similarSongs').html('<div align="center"><img src="/static/images/ajax-loader-big.gif"/></div>');
	$('#similarSongsBlock').css('display', '');
	$.getJSON('http://{{ siteHostname }}/channel/fetch/similarsongs?song='+escape(song)+'&artist='+escape(artist), loadSimilarSongList);
}

function fetchCallback(data,textStatus){
	if (data.song && data.artist) {
		getSimilarSongs(data.song, data.artist);
		setMovieData(data.videoTitle, data.videoID, data.artist, data.song);
	} else {
		setMovieData(data.videoTitle, data.videoID);
	}
	currentID = data.videoID;
	if (data.randomPlay) {
		setRandomTime();
	}
	playMovie(data.sourceURL);
}

function loadMovieDataByVideoID(videoID, artist, song) {
	if (artist != undefined && song != undefined) {
		moreQuery = '&artist='+artist+'&song='+song;
	} else {
		moreQuery = '';
	}
	$.getJSON("http://{{ siteHostname }}/channel/fetch?videoID="+videoID+moreQuery, fetchCallback);
}

function loadNextMovieData(random)
{
{% if not isPlaylist %}

	var random = false;
	var currIDStr = '';
	var randomStr = '';
	
	if (isInRandomTime()) {
		random = true;
	}
	
	if (currentID) {
		currIDStr = '&lastID='+currentID;
	} else {
		currIDStr = '';
	}
	
	if (random) {
		randomStr = '&random=1';
	} else {
		randomStr = '';
	}
	$.getJSON("http://{{ siteHostname }}/channel/fetch?channel={{ channel }}"+currIDStr+randomStr, fetchCallback);

{% else %}

	videoPlayIndex = (videoPlayIndex + 1) % videoList.length;
	var videoID = videoList[videoPlayIndex];
	$.getJSON("http://{{ siteHostname }}/channel/fetch?videoID="+videoID, fetchCallback);

{% endif %}
}

function bufferTimeout() {
	loadNextMovieData(true);
	clearBufferTimeout();
}

function startBufferTimeout() {
	if (null == bufferingTimeout) {
		bufferingTimeout = setTimeout("bufferTimeout();", 20000);
	}
}

function clearBufferTimeout() {
	if (bufferingTimeout) {
		clearTimeout(bufferingTimeout);
		bufferingTimeout = null;
	}
}

function stopVideo() {
}

/* register listeners */
function bufferHandler(obj)
{
	if (obj.percentage < 100) {
		startBufferTimeout();		
	}
}

function stateHandler(obj)
{
	if ('PLAYING' == obj.newstate) {
		clearBufferTimeout();
	} else if ('COMPLETED' == obj.newstate) {
		loadNextMovieData(false);
	}
}

function errorHandler(obj)
{
{% if not isPlaylist %}
	$('#recentlyPlayed li:first').remove();
{% endif %}
	startRandom();
}
/* initialize */
$(function(){
	var so = new SWFObject('/static/swf/jwplayer/player.swf',moviePlayerID,'{{ playerWidth }}','{{ playerHeight }}','9');
	so.addParam('allowscriptaccess','always');
	so.addParam('allowfullscreen','true');
    so.addParam("wmode", "transparent");
 	so.addParam('flashvars','&width={{ playerWidth }}&height={{ playerHeight }}&autostart=true');
	so.write('movieDiv');
	
{% if isPlaylist %}
	initVideoList();
{% endif %}

{% if edit %}
	editPlaylist();
{% endif %}

{% if not widget %}
	renderHighlightLink();
{% endif %}
});

/* called when the player is ready */
function playerReady(obj) {
	player = document[moviePlayerID];
	player.addModelListener('STATE', 'stateHandler');
	player.addModelListener('BUFFER', 'bufferHandler');
	player.addModelListener('ERROR', 'errorHandler');

{% if autoPlay %}
	loadNextMovieData(false);
{% endif %}
};

-->
</script>
